package com.qd.panda.service.card;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cdqidi.exception.ApiException;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.card.CardInfoShareDetailDTO;
import com.qd.common.panda.domain.entity.card.UserCardDTO;
import com.qd.panda.model.CardInfoDetail;
import com.qd.panda.model.UserCard;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 卡卷分享
 *
 * @author sjk
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserCardShareService {
    private final UserCardService userCardService;
    private final CardInfoDetailService cardInfoDetailService;
    private final CardInfoShareDetailService cardInfoShareDetailService;

    /**
     * 生成分享信息
     *
     * @param cardId 卡号
     * @param userId 分享人ID
     * @param mobile 分享人手机号
     * @return 分享ID
     */
    @Transactional(rollbackFor = Exception.class)
    public String shareCardId(String cardId, String userId, String mobile) {
        UserCard userCard = Optional.ofNullable(userCardService.getById(cardId)).orElseThrow(() -> new ApiException("卡劵ID值错误"));
        CardInfoDetail cardInfoDetail = Optional.ofNullable(cardInfoDetailService.getById(cardId)).orElseThrow(() -> new ApiException("卡劵ID值错误"));
        if (LocalDate.now().isAfter(userCard.getValidityEndTime())) {
            throw new ApiException("当前优惠劵已过期，无法分享");
        }
        if (userCard.getState() == PandaConstant.USE_STATE_2) {
            throw new ApiException("当前优惠劵已经使用，无法分享");
        }
        if (userCard.getState() == PandaConstant.USE_STATE_3) {
            throw new ApiException("当前优惠劵已过期，无法分享");
        }
//        if (collectCardService.existsByPlanId(cardInfoDetail.getPlanId())) {
//            throw new ApiException("已经配置了自动领卷，无法分享");
//        }
        if (!userCard.getUserId().equals(userId)) {
            log.error("分享人ID： {},劵对应人ID： {}", userId, userCard.getUserId());
            throw new ApiException("没有权限分享");
        }
        String shareId = cardInfoShareDetailService.getShareIdByCardId(cardId);
        if (StringUtils.hasLength(shareId)) {
            CardInfoShareDetailDTO cardInfoShareDetailDTO = new CardInfoShareDetailDTO();
            cardInfoShareDetailDTO.setShareId(shareId);
            cardInfoShareDetailDTO.setShareTime(LocalDateTime.now());
            cardInfoShareDetailService.update(cardInfoShareDetailDTO);
            cardInfoShareDetailDTO.freeData();
        } else {
            shareId = IdWorker.getIdStr();
            CardInfoShareDetailDTO cardInfoShareDetailDTO = new CardInfoShareDetailDTO();
            cardInfoShareDetailDTO.setShareId(shareId);
            cardInfoShareDetailDTO.setCardId(cardId);
            cardInfoShareDetailDTO.setCardMsgId(userCard.getCardMsgId());
            cardInfoShareDetailDTO.setPlanId(cardInfoDetail.getPlanId());
            cardInfoShareDetailDTO.setShareTime(LocalDateTime.now());
            cardInfoShareDetailDTO.setShareUserId(userId);
            cardInfoShareDetailDTO.setShareMobile(mobile);
            cardInfoShareDetailService.save(cardInfoShareDetailDTO);
            cardInfoShareDetailDTO.freeData();
        }

        return shareId;
    }

    /**
     * 领取卡卷
     *
     * @param shareId 分享ID
     * @param userId  领取人ID
     * @param mobile  领取人手机号
     */
    @Transactional(rollbackFor = Exception.class)
    public void receiveCardId(String shareId, String userId, String mobile) {
        CardInfoShareDetailDTO cardInfoShareDetailDTO = Optional.ofNullable(cardInfoShareDetailService.getByIdDto(shareId)).orElseThrow(() -> new ApiException("分享ID值错误"));
        if (StringUtils.hasLength(cardInfoShareDetailDTO.getReceivedUserId())) {
            throw new ApiException("当前优惠劵已被领取，无法领取");
        }
//        if (collectCardService.existsByPlanId(cardInfoShareDetailDTO.getPlanId())) {
//            throw new ApiException("已经配置了自动领卷，不支持领取卡券");
//        }
        UserCardDTO userCard = Optional.ofNullable(userCardService.getByIdDto(cardInfoShareDetailDTO.getCardId())).orElseThrow(() -> new ApiException("卡劵ID值错误"));
        if (LocalDate.now().isAfter(userCard.getValidityEndTime())) {
            throw new ApiException("当前优惠劵已过期，无法领取");
        }
        if (userCard.getState() == PandaConstant.USE_STATE_2) {
            throw new ApiException("当前优惠劵已经使用，无法领取");
        }
        if (userCard.getState() == PandaConstant.USE_STATE_3) {
            throw new ApiException("当前优惠劵已过期，无法领取");
        }
        if (userCard.getUserId().equals(userId)) {
            throw new ApiException("送都送了，还想收回来？");
        }
        cardInfoShareDetailDTO.setReceivedUserId(userId);
        cardInfoShareDetailDTO.setReceivedMobile(mobile);
        cardInfoShareDetailDTO.setReceivedTime(LocalDateTime.now());
        cardInfoShareDetailService.update(cardInfoShareDetailDTO);
        cardInfoShareDetailDTO.freeData();

        userCard.setUserId(userId);
        userCardService.update(userCard);
        userCard.freeData();
    }

    @Transactional(readOnly = true)
    public Map<String, Object> cardInfoByShareId(String shareId) {
        CardInfoShareDetailDTO cardInfoShareDetailDTO = Optional.ofNullable(cardInfoShareDetailService.getByIdDto(shareId)).orElseThrow(() -> new ApiException("分享ID值错误"));
        UserCardDTO userCard = Optional.ofNullable(userCardService.getByIdDto(cardInfoShareDetailDTO.getCardId())).orElseThrow(() -> new ApiException("卡劵ID值错误"));
        boolean isReceive = StringUtils.hasLength(cardInfoShareDetailDTO.getReceivedUserId());
        Map<String, Object> map = new HashMap<>(2);
        map.put("userCardInfo", userCard);
        map.put("isReceive", isReceive);
        return map;
    }
}
